package com.dms.common.utils;

import com.dms.common.config.OssConfig;
import com.dms.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class FileUploadUtils {
    private final OssUtils ossUtils;
    private final OssConfig ossConfig;

    @Value("${upload.base-path}")
    private String uploadPath;

    @Value("${upload.allowed-types}")
    private String allowedTypes;

    @Value("${upload.max-size}")
    private long maxSize;

    public FileUploadUtils(OssUtils ossUtils, OssConfig ossConfig) {
        this.ossUtils = ossUtils;
        this.ossConfig = ossConfig;
    }

    public String uploadAvatar(MultipartFile file) throws Exception {
        return ossUtils.uploadFile(file, "avatars");
    }

    public String uploadProductImage(MultipartFile file) throws Exception {
        return ossUtils.uploadFile(file, "products");
    }

    public void deleteFile(String fileUrl) {
        ossUtils.deleteFile(fileUrl);
    }

    /**
     * 通用文件上传方法
     * @param file 文件
     * @param directory 目标目录
     * @return 文件URL
     * @throws Exception 上传异常
     */
    public String uploadFile(MultipartFile file, String directory) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !allowedTypes.contains(contentType)) {
            throw new BusinessException("不支持的文件类型");
        }

        // 检查文件大小
        if (file.getSize() > maxSize) {
            throw new BusinessException("文件大小超过限制");
        }

        return ossUtils.uploadFile(file, directory);
    }

    /**
     * 上传图片
     * @param file 图片文件
     * @return 图片URL
     */
    public String uploadImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !allowedTypes.contains(contentType)) {
            throw new BusinessException("不支持的文件类型");
        }

        // 检查文件大小
        if (file.getSize() > maxSize) {
            throw new BusinessException("文件大小超过限制");
        }

        try {
            String fileName = UUID.randomUUID().toString() + getFileExtension(file.getOriginalFilename());
            String filePath = uploadPath + File.separator + fileName;
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return fileName;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 删除图片
     * @param imageUrl 图片URL
     * @return 是否删除成功
     */
    public boolean deleteImage(String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            return false;
        }

        try {
            File file = new File(uploadPath + File.separator + imageUrl);
            return file.delete();
        } catch (Exception e) {
            log.error("删除文件失败: {}", imageUrl, e);
            return false;
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf(".");
        return lastDotIndex == -1 ? "" : fileName.substring(lastDotIndex);
    }
} 